package com.hy.wsroom.service;

import com.hy.wsroom.entity.Client;
import com.hy.wsroom.entity.Message;
import com.hy.wsroom.entity.Room;
import com.hy.wsroom.util.ClientHolder;
import com.hy.wsroom.util.JSONUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hy
 * 处理客户端服务类
 */
@Data
@Service
@RequiredArgsConstructor
public class WebSocketClient {
    private final Map<String, Room> roomMap = new ConcurrentHashMap<>();
    private final Map<String, Client> clientMap = new ConcurrentHashMap<>();

    public void addClient(Client client) {
        clientMap.put(client.getId(), client);
    }

    public void removeClient(Client client) {
        clientMap.remove(client.getId());
    }

    public void addRoom(Room room) {
        roomMap.put(room.getRoomId(), room);
    }

    public void removeRoom(Room room) {
        roomMap.remove(room.getRoomId());
    }

    public void addClientToRoom(String roomId, Client client) {
        Room room = roomMap.get(roomId);
        if (Objects.nonNull(room)) {
            room.addClient(client);
        }
    }



    // 发送消息
    public void sendTextMessage(Message message) throws IOException {
        if (message.isBroadcast()) {
            String roomId = message.getRoomId();
            if (Objects.nonNull(roomId)) {
                sendTextMessageByRoomId(roomId, message);
            }
        }
    }

    public void sendTextMessageByClientId(String clientId, String type, String text) throws IOException {
        Client toClient = clientMap.get(clientId);
        if (Objects.isNull(toClient)) {
            throw new RuntimeException("客户端不存在");
        }
        Message message = new Message();
        message.setBroadcast(false);
        message.setContent(text);
        message.setFromClient(ClientHolder.get());
        message.setFrom(ClientHolder.getClientId());
        message.setTo(clientId);
        message.setToClient(toClient);
        message.setType(type);
        sendTextMessage(message);

    }

    private void sendTextMessageByRoomId(String roomId, Message message) {
        Room room = roomMap.get(roomId);
        if (Objects.nonNull(room)) {
            for (Client client : room.getClients()) {
                try {
                    client.getSession().sendMessage(new TextMessage(JSONUtil.toJSON(message)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
